<style lang="less" scoped>
	.music {
		width: 100%;
		height: 667px;
		background: linear-gradient(to bottom, #585252, #2d2b29);

		.main {
			position: absolute;
			bottom: 7%;
			width: 100%;

			.container {
				width: 90%;
				margin: 0 auto;
				position: relative;

				.love {
					position: absolute;
					right: 50px;
					top: -60px;
				}

				.comment {
					position: absolute;
					right: 0;
					top: -60px;
				}

				.time {
					margin-top: 7px;
					display: flex;
					justify-content: space-between;
					color: #bdbdbd;
					font-size: 12px;
				}

				.row {
					width: 100%;
					margin-top: 30px;
					display: flex;
					justify-content: space-between;

					div {
						width: 10%;

						img {
							width: 100%;
						}
					}

					.playAndPause {
						margin-top: -10px;
						width: 16%;

						img {
							width: 100%;
						}
					}
				}
			}
		}
	}
</style>
<template>
	<view class="music">
		<music-top></music-top>
		<!-- 唱片 -->
		<record :detail="musicDetail" @click="isLyric" v-if="!isShow"></record>
		<!-- 歌词 -->
		<lyric :obj='lyricObj' :time="time" @click="isLyric" v-else-if="isShow"></lyric>
		<div class="main">
			<div class="container">
				<div class="love" @click="addCollect(id)" v-if="!isShow">
					<uni-icons type="heart" size="30" color="#fefefe" v-if="!isCollect"></uni-icons>
					<uni-icons type="heart-filled" size="30" color="#fb4841" v-else-if="isCollect"></uni-icons>
				</div>
				<div class="comment" v-if="!isShow">
					<uni-icons type="chatbubble" size="30" color="#fefefe"></uni-icons>
				</div>
				<div class="progress">
					<view class="progress-box">
						<progress :percent="this.precent" stroke-width="3" backgroundColor="#b8b8b8"
							activeColor="#fefefe" />
					</view>
					<div class="time">
						<div class="nowTime">
							<span>{{curTime}}</span>
						</div>
						<div class="tolTime">
							<span>{{musicDetail[0].tolTime}}</span>
						</div>
					</div>
				</div>
				<div class="loading" v-if="isLoading" style="position: absolute; top: -200%;left:30%;">
					<loading></loading>
				</div>
				<div class="row">
					<div class="playFn">
						<img src="../../static/reload.png" alt="" />
					</div>
					<div class="pre" @click="pre">
						<img src="../../static/play-previous.png" alt="" />
					</div>
					<div class="playAndPause" @click="play">
						<img src="../../static/play.png" alt="" v-if="!isPlay" />
						<img src="../../static/pause.png" alt="" v-else-if="isPlay" />
					</div>
					<div class="next" @click="next">
						<img src="../../static/play-next.png" alt="" />
					</div>
					<div class="list">
						<img src="../../static/musicList.png" alt="" />
					</div>
				</div>
			</div>
		</div>
	</view>
</template>

<script>
	import musicTop from '../../components/musicTop.vue'
	import record from '../../components/record.vue'
	import lyric from '../../components/lyric.vue'
	import loading from '../../components/loading.vue'
	import {
		getMusicDetail
	} from '../../api/request'
	import {
		getMusicUrl
	} from '../../api/request'
	export default {
		components: {
			musicTop,
			record,
			lyric,
			loading
		},
		data() {
			return {
				isPlay: false,
				musicDetail: [],
				musicUrl: '',
				tolTime:0,
				id: '',
				innerAudioContext: {},
				lyricObj: {},
				isShow: false,
				curTime: '00:00',
				precent: 0,
				timer: {},
				time: 0,
				isCollect: false,
				SongList:[],
				listIndex:0,
				isLoading:false,
			}
		},
		async onLoad(options) {
			this.getData(options)
			// 判断有没有收藏
			this.hasCollect(this.id)
			this.getSongList()
			await this.getMusicDetailFn(this.id)
			await this.setMusic()
			await this.onTimeUpdateFn()
			await this.play()
		},
		methods: {
			getData(options) {
				this.id = options.id
				this.musicUrl = `https://music.163.com/song/media/outer/url?id=${this.id}.mp3 `
				this.lyricObj.id = this.id
			},
			async play() {
				this.isPlay = !this.isPlay
				if (this.isPlay) {
					this.innerAudioContext.play()
					this.timer = setInterval(() => {
						this.getCurrentTime()
					}, 1000)
					// console.log('222')
				} else {
					this.innerAudioContext.pause()
					clearInterval(this.timer)
					this.timer = null
				}
				this.musicDetail[1] = this.isPlay
				this.lyricObj.isPlay = this.isPlay
			},
			async getMusicDetailFn(ids) {
				this.isLoading=true
				await getMusicDetail({
						ids
					})
					.then(
						(data) => {
							let {
								songs
							} = data;
							let newArr = songs.map(item => {
								let obj = {}
								obj.id = item.id
								obj.name = item.name;
								obj.author = item.ar[0].name;
								obj.picUrl = item.al.picUrl
								this.tolTime=item.dt/1000
								let m = Math.floor(item.dt / 1000 / 60)
								let s = Math.ceil(item.dt / 1000 % 60)
								m = m >= 10 ? m : "0" + m
								s = s >= 10 ? s : "0" + s
								obj.tolTime = `${m}:${s}`
								return obj
							})
							this.musicDetail = newArr
							this.musicDetail.push(this.isPlay)
							// console.log('result-->'+JSON.stringify(songs[0].dt))
						}
					)
			},
			async setMusic() {
				this.innerAudioContext = uni.createInnerAudioContext();
				this.innerAudioContext.autoplay = false;
				this.innerAudioContext.src = `https://music.163.com/song/media/outer/url?id=${this.id}.mp3 `;
			},
			isLyric() {
				this.isShow = !this.isShow
			},
			getCurrentTime() {
				let curTime = this.innerAudioContext.currentTime
				this.time = curTime
				let tolTime = this.innerAudioContext.duration
				this.precent = curTime /this.tolTime * 100
				// console.log(curTime)
				let m = Math.floor(curTime / 60)
				let s = Math.ceil(curTime % 60)
				m = m >= 10 ? m : "0" + m
				s = s >= 10 ? s : "0" + s
				this.curTime = `${m}:${s}`
				// console.log(this.precent)
			},
			async onTimeUpdateFn() {
				this.innerAudioContext.onTimeUpdate()
				this.isLoading=false
			},
			hasCollect(id) {
				let token = localStorage.getItem("AUTO_TOKEN");
				if (id == "") return;
				if (token) {
					// 收藏的音乐数据
					let CollectSongs = JSON.parse(localStorage.getItem("CollectSongs")) 
					if (CollectSongs) {
						// console.log('123:'+CollectSongs[0])
						let isCollected = false;
						// 循环数组
						for (let i = 0; i < CollectSongs.length; i++) {
							// console.log(CollectSongs[i].id)
							if (CollectSongs[i].id == id) {
								// console.log('2')
								isCollected = true;
							}
						}
						this.isCollect = isCollected;
					}
				}
			},
			// 点击 “收藏” 
			addCollect(id) {
				let token = localStorage.getItem("AUTO_TOKEN");
				let CollectSongs = JSON.parse(localStorage.getItem("CollectSongs")) ;
				
				if (token) {
					// 判断布尔值
					if (this.isCollect) {
						// 已收藏
						// 设置布尔值为false (取消收藏)
						this.isCollect = false;
						if (CollectSongs) {
							let newSongs = CollectSongs.filter(item => {
								return item.id != id
							})
							// 重新赋值
							CollectSongs = newSongs;
							// 把这个all数据转成字符串存储在本地
							localStorage.setItem("CollectSongs", JSON.stringify(CollectSongs));
						}
					} else {
						// 没有收藏
						// 设置布尔值为true（设置收藏）
						this.isCollect = true;
						// 整合数据
						
						
						// 添加收藏歌曲数据
						if (CollectSongs == undefined) {
							
							CollectSongs = []
							CollectSongs.push(this.musicDetail[0]);
						} else {
							
							CollectSongs.push(this.musicDetail[0]);
						}
						
						localStorage.setItem("CollectSongs", JSON.stringify(CollectSongs));
					}
				} else {
					uni.showToast({
						title: '请登录后再进行收藏',
						icon: 'none'
					})
				}
			},
			// 拿取当前播放列表
			getSongList(){
				let SongList=localStorage.getItem('SongList')
				this.SongList=JSON.parse(SongList)
				for(let i=0;i<this.SongList.length;i++){
					if(this.SongList[i].id==this.id){
						this.listIndex=i
					}
				}
				// console.log("-->"+this.listIndex)
			},
			async pre(){
				this.innerAudioContext.destroy()
				let index=this.listIndex-1
				this.listIndex-=1
				console.log('index:'+index)
				let SongList=this.SongList
				if(index==-1){
					index=SongList.length-1
				}
				for(let i=0;i<SongList.length;i++){
					if(i==index){
						this.id=SongList[i].id
						this.isPlay=false
						await this.getMusicDetailFn(this.id)
						await this.setMusic()
						await this.onTimeUpdateFn()
						await this.play()
					}
				}
				this.hasCollect(this.id)
			},
			async next(){
				this.innerAudioContext.destroy()
				let index=this.listIndex+1
				this.listIndex+=1
				// console.log('index:'+index)
				let SongList=this.SongList
				if(index==(SongList.length-1)){
					index=0
				}
				for(let i=0;i<SongList.length;i++){
					if(i==index){
						this.id=SongList[i].id
						this.isPlay=false
						await this.getMusicDetailFn(this.id)
						await this.setMusic()
						await this.onTimeUpdateFn()
						await this.play()
					}
				}
				this.hasCollect(this.id)
			}
		},
		filters: {
			formatime(value) {
				let m = 0;
				let s = 0;
				m = Math.floor(value % 3600 / 60);
				s = Math.floor(value % 60);
				m = m < 10 ? '0' + m : m;
				s = s < 10 ? '0' + s : s;
				return `${m}:${s}`;
			}
		},
	}
</script>